package cn.tedu.medicalmanagementsystem.user.service.impl;

import cn.tedu.medicalmanagementsystem.base.response.JsonResult;
import cn.tedu.medicalmanagementsystem.base.response.StatusCode;
import cn.tedu.medicalmanagementsystem.manager.pojo.entity.Appointment;
import cn.tedu.medicalmanagementsystem.user.mapper.UserAppointmentMapper;
import cn.tedu.medicalmanagementsystem.user.mapper.ReviewMapper;
import cn.tedu.medicalmanagementsystem.user.mapper.UserMapper;
import cn.tedu.medicalmanagementsystem.user.pojo.entity.User;
import cn.tedu.medicalmanagementsystem.user.pojo.dto.ReviewAddParam;
import cn.tedu.medicalmanagementsystem.escort.pojo.dto.ReviewReplyParam;
import cn.tedu.medicalmanagementsystem.user.pojo.entity.Review;
import cn.tedu.medicalmanagementsystem.user.pojo.vo.PageData;
import cn.tedu.medicalmanagementsystem.user.pojo.vo.ReviewVO;
import cn.tedu.medicalmanagementsystem.user.pojo.vo.UserAppointmentVO;
import cn.tedu.medicalmanagementsystem.user.service.ReviewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j  // 添加这个注解来自动生成log变量
@Service
public class ReviewServiceImpl implements ReviewService {
    @Autowired
    private ReviewMapper reviewMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAppointmentMapper userAppointmentMapper;

    @Override
    @Transactional
    public JsonResult addReview(ReviewAddParam param, Long userId) {
        try {
            List<UserAppointmentVO> appointments = userAppointmentMapper.selectByUserId(userId);
            if (appointments == null || appointments.isEmpty()) {
                return JsonResult.fail(StatusCode.OPERATION_FAIL, "预约不存在");
            }

            if (reviewMapper.existsById(param.getAppointmentId())) {
                return JsonResult.fail(StatusCode.OPERATION_FAIL, "您已经评价过该次服务");
            }

            User user = userMapper.selectById(userId);
            if (user == null) {
                return JsonResult.fail(StatusCode.USER_NOT_EXIST);
            }

            Review review = new Review();
            BeanUtils.copyProperties(param, review);
            review.setUserId(userId);
            review.setUserName(user.getUsername());
            review.setCreateTime(new Date());

            int rows = reviewMapper.insert(review);
            if (rows != 1) {
                return JsonResult.fail(StatusCode.OPERATION_FAILED, "评价失败");
            }

            reviewMapper.updateEscortRating(review.getEscortId());
            return JsonResult.ok("评价成功");
        } catch (Exception e) {
            log.error("添加评价失败", e);
            return JsonResult.fail(StatusCode.SYSTEM_ERROR, "系统异常，请稍后再试");
        }
    }

    @Override
    @Transactional
    public JsonResult replyReview(ReviewReplyParam param, Long escortId) {
        try {
            if (!reviewMapper.existsByIdAndEscortId(param.getReviewId(), escortId)) {
                return JsonResult.fail(StatusCode.OPERATION_FAIL, "无权回复此评价");
            }

            int rows = reviewMapper.updateReply(
                    param.getReviewId(),
                    escortId,
                    param.getReplyContent()
            );

            if (rows != 1) {
                return JsonResult.fail(StatusCode.OPERATION_FAILED, "回复失败");
            }
            return JsonResult.ok("回复成功");
        } catch (Exception e) {
            log.error("回复评价失败", e);
            return JsonResult.fail(StatusCode.SYSTEM_ERROR, "系统异常，请稍后再试");
        }
    }

    @Override
    public JsonResult<List<ReviewVO>> getReviewsByUserId(Long userId) {
        try {
            List<ReviewVO> reviews = reviewMapper.selectByUserId(userId);
            return JsonResult.ok(reviews);
        } catch (Exception e) {
            log.error("获取用户评价列表失败", e);
            return JsonResult.fail(StatusCode.SYSTEM_ERROR, "获取评价列表失败");
        }
    }

    @Override
    public JsonResult<List<ReviewVO>> getReviewsByEscortId(Long escortId) {
        try {
            List<ReviewVO> reviews = reviewMapper.selectByEscortId(escortId);
            return JsonResult.ok(reviews);
        } catch (Exception e) {
            log.error("获取陪诊员评价列表失败", e);
            return JsonResult.fail(StatusCode.SYSTEM_ERROR, "获取评价列表失败");
        }
    }
    @Override
    public JsonResult<PageData<ReviewVO>> listReviews(Long userId, Long escortId, Integer minRating,
                                                      Integer maxRating, Boolean replied, Integer page, Integer size) {
        try {
            int offset = (page - 1) * size;
            List<ReviewVO> reviews = reviewMapper.selectReviewsWithPage(
                    userId, escortId, minRating, maxRating, replied, offset, size);
            int total = reviewMapper.countReviews(
                    userId, escortId, minRating, maxRating, replied);

            PageData<ReviewVO> pageData = new PageData<>();
            pageData.setList(reviews);
            pageData.setTotal(total);
            pageData.setPage(page);
            pageData.setSize(size);

            return JsonResult.ok(pageData);
        } catch (Exception e) {
            log.error("分页查询评价列表失败", e);
            return JsonResult.fail(StatusCode.SYSTEM_ERROR, "获取评价列表失败");
        }
    }

    // 保留旧方法实现以兼容性，或直接删除
    @Override
    @Deprecated
    public JsonResult<List<ReviewVO>> getUserReviewsByEscortId(Long escortId) {
        return getReviewsByEscortId(escortId);
    }
}